<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .action div{background-color: pink; padding: 10px; cursor: pointer; color: white; margin: 10px 0; display: inline-block;}
        .screen-capture{visibility: hidden;}
        img{margin-right: 10px;}
    </style>
</head>
<body>
<div class="action">
    <div class="open-video ">开/关闭摄像头</div>
    <div class="screen-capture">截屏</div>
</div>
<video autoplay playsinline></video>
<div class="show-img"></div>
<script type="module">
  import {getUserMedia, screenCapture} from './navigator-helper.js';
  const openVideoEl = document.querySelector('.open-video');// 打开摄像头按钮
  let localMediaStream = null; //本地多媒体工具，如摄像头或者麦克风（流）
  const screenCaptureEl = document.querySelector('.screen-capture'); // 截屏按钮
  const videoEl = document.querySelector('video');// 视频框

  // 打开摄像头点击事件
  openVideoEl.onclick = async function(){
    // 关闭摄像头、隐藏截屏按钮
    if(localMediaStream){
      localMediaStream.getTracks().forEach(element => {element.stop(); });
      screenCaptureEl.style.visibility = 'hidden';
      localMediaStream = null;
      return false;
    }
    //拿到本地媒体流，并显示到video元素中
    localMediaStream = await getUserMedia();
    videoEl.srcObject = localMediaStream;
    screenCaptureEl.style.visibility = 'visible';
  }

  // 截屏点击事件
  const showImg = document.querySelector('.show-img');
  screenCaptureEl.onclick = () =>{
    const imgBase64 = screenCapture(videoEl);
    const img = document.createElement('IMG');
    img.src = imgBase64;
    showImg.appendChild(img)
  }
</script>
</body>
</html>
